package org.example.controller;

import org.example.entity.User;
import org.example.entity.UpdateUser;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 创建用户
     */
    @PostMapping
    public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
        try {
            User createdUser = userService.createUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        Optional<User> user = userService.findById(id);
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取所有用户
     */
    @GetMapping
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userService.findAllUsers();
        return ResponseEntity.ok(users);
    }
    
    /**
     * 根据状态获取用户
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<User>> getUsersByStatus(@PathVariable Integer status) {
        List<User> users = userService.findUsersByStatus(status);
        return ResponseEntity.ok(users);
    }
    
    /**
     * 根据昵称搜索用户
     */
    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsersByNickname(@RequestParam String nickname) {
        List<User> users = userService.searchUsersByNickname(nickname);
        return ResponseEntity.ok(users);
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/{id}/avatar")
    public ResponseEntity<?> uploadAvatar(@PathVariable Long id, @RequestParam("avatar") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的头像文件");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResponseEntity.badRequest().body("只能上传图片文件");
            }

            // 检查文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest().body("头像文件大小不能超过5MB");
            }

            // 检查用户是否存在
            Optional<User> existingUser = userService.findById(id);
            if (!existingUser.isPresent()) {
                return ResponseEntity.notFound().build();
            }

            // 创建头像存储目录
            String uploadDir = "uploads/avatars/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null && originalFilename.contains(".")
                ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : ".jpg";
            String uniqueFilename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 更新用户头像路径
            String avatarUrl = "/api/avatars/" + uniqueFilename;
            User user = new User();
            user.setId(id);
            user.setAvatar(avatarUrl);

            User updatedUser = userService.updateUser(user);

            // 返回完整的头像URL供前端使用
            return ResponseEntity.ok(new AvatarUploadResponse("头像上传成功", uniqueFilename, avatarUrl));

        } catch (IOException e) {
            System.err.println("头像上传失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("头像上传失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("头像上传异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("头像上传失败: " + e.getMessage());
        }
    }


    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @Validated(UpdateUser.class) @RequestBody User user) {
        try {
            System.out.println("用户更新请求 - 用户ID: " + id);
            System.out.println("请求数据: " + user);
            System.out.println("用户名: " + user.getUsername());
            System.out.println("昵称: " + user.getNickname());
            System.out.println("邮箱: " + user.getEmail());
            System.out.println("电话: " + user.getPhone());
            
            user.setId(id);
            User updatedUser = userService.updateUser(user);
            System.out.println("用户信息更新成功: " + updatedUser.getUsername());
            return ResponseEntity.ok(updatedUser);
        } catch (RuntimeException e) {
            System.err.println("用户信息更新失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            System.err.println("用户信息更新异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误: " + e.getMessage());
        }
    }
    
    /**
     * 更新密码
     */
    @PutMapping("/{id}/password")
    public ResponseEntity<?> updatePassword(@PathVariable Long id, @RequestBody PasswordUpdateRequest request) {
        try {
            userService.updatePassword(id, request.getOldPassword(), request.getNewPassword());
            return ResponseEntity.ok("密码更新成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 重置密码
     */
    @PutMapping("/{id}/reset-password")
    public ResponseEntity<?> resetPassword(@PathVariable Long id, @RequestBody PasswordResetRequest request) {
        try {
            userService.resetPassword(id, request.getNewPassword());
            return ResponseEntity.ok("密码重置成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long id, @RequestBody StatusUpdateRequest request) {
        try {
            userService.updateUserStatus(id, request.getStatus());
            return ResponseEntity.ok("用户状态更新成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 更新用户角色
     */
    @PutMapping("/{id}/role")
    public ResponseEntity<?> updateUserRole(@PathVariable Long id, @RequestBody RoleUpdateRequest request) {
        try {
            userService.updateUserRole(id, request.getRole());
            return ResponseEntity.ok("用户角色更新成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 统计活跃用户数量
     */
    @GetMapping("/stats/active")
    public ResponseEntity<Long> getActiveUserCount() {
        long count = userService.countActiveUsers();
        return ResponseEntity.ok(count);
    }

    /**
     * 获取用户使用天数
     */
    @GetMapping("/{id}/usage-days")
    public ResponseEntity<Long> getUserUsageDays(@PathVariable Long id) {
        try {
            long usageDays = userService.getUserUsageDays(id);
            return ResponseEntity.ok(usageDays);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(0L);
        }
    }

    /**
     * 获取用户使用天数（到指定日期）
     */
    @GetMapping("/{id}/usage-days/{targetDate}")
    public ResponseEntity<Long> getUserUsageDaysByDate(@PathVariable Long id, @PathVariable String targetDate) {
        try {
            // 解析日期字符串，格式：yyyy-MM-dd
            LocalDateTime dateTime = LocalDateTime.parse(targetDate + "T00:00:00");
            long usageDays = userService.getUserUsageDaysByDate(id, dateTime);
            return ResponseEntity.ok(usageDays);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(0L);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(0L);
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            return ResponseEntity.ok("用户删除成功");
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    // 内部类用于请求体
    public static class PasswordUpdateRequest {
        private String oldPassword;
        private String newPassword;
        
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
    
    public static class PasswordResetRequest {
        private String newPassword;
        
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
    
    public static class StatusUpdateRequest {
        private Integer status;
        
        public Integer getStatus() { return status; }
        public void setStatus(Integer status) { this.status = status; }
    }

    public static class RoleUpdateRequest {
        private String role;
        
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
    }
    
    public static class UserUpdateRequest {
        private String username;
        private String nickname;
        private String email;
        private String phone;
        private String avatar;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }

        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }

        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }

        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }

        public String getAvatar() { return avatar; }
        public void setAvatar(String avatar) { this.avatar = avatar; }
    }

    /**
     * 头像上传响应类
     */
    public static class AvatarUploadResponse {
        private String message;
        private String filename;
        private String avatarUrl;
        private boolean success;

        public AvatarUploadResponse(String message, String filename, String avatarUrl) {
            this.message = message;
            this.filename = filename;
            this.avatarUrl = avatarUrl;
            this.success = true;
        }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }

        public String getFilename() { return filename; }
        public void setFilename(String filename) { this.filename = filename; }

        public String getAvatarUrl() { return avatarUrl; }
        public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; }

        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
    }
}
